<script setup lang="ts">
import {
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NForm,
  NFormItem,
  NModal,
  NSelect,
  useMessage,
  NDatePicker,
  NRadioGroup,
  NRadio
} from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import TableView from '@/components/TableView.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination, HttpResponse } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { useRouter } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import dayjs from 'dayjs'
import { t } from '@wangeditor/editor'

const message = useMessage()
const router = useRouter()

onMounted(async () => {
  await getInterpreterOptions()
  queryTableData(true)
})

const attendOptions = [
  { value: 1, label: '统计' },
  { value: 0, label: '不统计' }
]

const paginationReactive = reactive({
  date: null,
  interpreterId: null,
  attendFlag: 1,
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const interpreterOptions = ref<any>([])
const getInterpreterOptions = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'interpreter',
    api: 'interpreterList',
    override: {
      params: {}
    }
  })
  if (error) return message.error(error.message)
  interpreterOptions.value = [
    { value: '-1', label: '全部' },
    ...res.data.list.map((r: any) => {
      return {
        value: r.identifyingId,
        label: r.interpreterName
      }
    })
  ]
}
const tableData = ref<InterpreterModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<InterpreterModel>>({
      module: 'interpreter',
      api: 'statisticsList',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          attendFlag: paginationReactive.attendFlag,
          startWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
          endWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
          interpreterId: paginationReactive.interpreterId === -1 ? null : paginationReactive.interpreterId
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}
const exportData = async () => {
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'interpreter',
    api: 'exportStatisticsList',
    override: {
      data: {
        limit: paginationReactive.pageSize,
        page: paginationReactive.page,
        attendFlag: paginationReactive.attendFlag,
        startWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
        endWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
        interpreterId: paginationReactive.interpreterId === -1 ? null : paginationReactive.interpreterId
      }
    }
  })
  if (error) return message.error(error.message)
  download(headers, res, '考勤记录')
  message.success('导出成功')
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const columns: DataTableColumns<InterpreterModel> = [
  {
    title: '讲解员姓名',
    key: 'interpreterName',
    align: 'center'
  },
  {
    title: '服务次数',
    key: 'conNumber',
    align: 'center'
  },
  {
    title: '服务天数',
    key: 'serviceDays',
    align: 'center'
  },
  {
    title: '服务人数',
    key: 'servicePeopleNumber',
    align: 'center'
  },
  {
    title: '服务团队数',
    key: 'serviceTeamNumber',
    align: 'center'
  },
  {
    title: '团队讲解明细',
    key: 'attendFlag',
    align: 'center',
    render: (row: any, index) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({ path: '/interpreter/record', query: { interpreterName: row.interpreterName } })
          }
        },
        {
          default: () => '跳转'
        }
      ),
    ]
  }
]

</script>

<template>
  <div class="interpreter_record_container">
    <div class="interpreter_record_form">
      <NForm ref="formRef" inline label-placement="left" :model="paginationReactive">
        <NFormItem label="统计日期：" path="date">
          <NDatePicker v-model:value="paginationReactive.date" type="daterange" clearable />
        </NFormItem>
        <NFormItem label="讲解员：" path="status">
          <NSelect style="width: 150px;" v-model:value="paginationReactive.interpreterId" :options="interpreterOptions"
            placeholder="请选择是否到场" clearable />
        </NFormItem>
        <NFormItem label="是否统计未到场：" path="teamName">
          <NRadioGroup v-model:value="paginationReactive.attendFlag" name="radiogroup">
            <NSpace>
              <NRadio v-for="song in attendOptions" :key="song.value" :value="song.value">
                {{ song.label }}
              </NRadio>
            </NSpace>
          </NRadioGroup>
        </NFormItem>
        <NFormItem>
          <NButton style="margin-right: 10px;" type="primary" @click="queryTableData(false)">
            查找
          </NButton>
          <NButton type="primary" @click="exportData">
            导出
          </NButton>
        </NFormItem>
      </NForm>
    </div>
    <div class="interpreter_record_table">
      <NDataTable :columns="columns" :data="tableData" :pagination="false" :bordered="false" flex-height
        style="height: 100%;" />
    </div>
    <div class="interpreter_record_pagination">
      <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize">
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
.interpreter_record_container {
  height: 100%;
  padding: 30rem;

  .interpreter_record_form {
    height: 7%;
  }

  .interpreter_record_table {
    height: 87%;
  }

  .interpreter_record_pagination {
    height: 6%;
  }
}
</style>
